/**
 * 合同的编辑和添加
 */
//合同id
var contractid = 0;
$(function() {
	//时间
	$("#contract_date,#stocking_time_limit,#transport_time_limit,#stocking_time_limit,#TTprepay_date,#remind_alarm_time").datepicker( $.datepicker.regional[ "zh-CN" ] );

	//列表tab
	$( "#tabs" ).tabs({
		collapsible: true,
		select: function(event, ui){
			showGrid(event, ui);
		}
	});
	//按钮
	$("button").button();
	window.contractid = $("#id").val();

	//联动
	choiseCustomer();
	choiseCustomerAgent();
	choiseCurrency();
	
	//window.grids = $("#product_list").flexigrid({
	initGrid(null,$("#product_list"));
});

var
noused = {}
//附属数据参数列表
,attachmentItems = {
	"product" : {
		"gridArg":{
			"url":BASEURL + "/contract/listproduct/contractid/"+$("#id").val()
			,"colModel" : [
				{display: 'ID', name : 'id', width : 20, sortable : true, align: 'center'},
				//{display: '编号', name : 'code', width : 80, sortable : false, align: 'left'},
				//{display: '条形码', name : 'barcode', width : 80, sortable : true, align: 'left'},
				//{display: '名称', name : 'name_cn', width : 80, sortable : true, align: 'left'},
				{display: '英文名称', name : 'name_en', width : 80, sortable : true, align: 'left'},
				{display: '规格', name : 'specification', width : 80, sortable : true, align: 'left'},
				{display: '图片', name : 'picture', width : 80, sortable : true, align: 'left'},			
				{display: '成本', name : 'cost', width : 80, sortable : false, align: 'left',process:gridHelper.Cash},
				{display: '售价', name : 'price', width : 80, sortable : true, align: 'left',process:gridHelper.Cash}				
			]
		}
		,"addArg":{
			"url":BASEURL + "/contract/addproduct/contractid/"+$("#id").val()
			,"dialog":{"title":"新增产品"}
		}
		,"editArg":{
			"url":BASEURL + "/contract/editproduct/id/{id}"
			,"dialog":{"title":"修改产品"}
		}
		,"delurl":BASEURL + "/contract/delproduct"
	}
	,"attachment" :{
		"gridArg":{
			"url":BASEURL + "/contractattachment/listbycontract/contractid/"+$("#id").val()
			,"colModel" :[
					{display: 'ID', name : 'id', width : 20, sortable : true, align: 'center'},
					{display: '附件英文名', name : 'name_en', width : 100, sortable : true, align: 'left'},
					{display: '附件中文名', name : 'name_cn', width : 100, sortable : true, align: 'left'},
					{display: '附件类型', name : 'filepath', width : 30, sortable : true, align: 'left',process:gridHelper.Extention},			
					{display: '备注', name : 'note', width : 150, sortable : true, align: 'left'}				
				]
		}
		,"addArg":{
			"url":BASEURL + "/contractattachment/add/contractid/"+$("#id").val()
			,"dialog":{"title":"新增附件"}
			,"afterRenderCreatForm":function(){
				var upTagId = zendform.uploadTag($("#filepath"));//设置swfupload附着的element
				appendSWFupload({
					"button_placeholder_id":upTagId//设置swfupload按钮附着的element，它来自上一条语句
					,"upload_start_handler":function(){
						//开始上传
						zendform.uploadingTag($("#filepath"));
					}
					,"upload_error_handler":function(file, errorCode, message){
						//上传出错时
						alert("上传错误："+message);
						$("#filepath").next(".uploading").remove();
					}
				},{
					"ju_element":"filepath" //通知上传的额外参数，这里的ju_element必须以ju开头，是返回值的复制element
				});
			}
		}
		,"editArg":{
			"url":BASEURL + "/contractattachment/edit/id/{id}"
			,"dialog":{"title":"修改附件"}
			,"afterRenderCreatForm":function(){
				var upTagId = zendform.uploadTag($("#filepath"));//设置swfupload附着的element
				appendSWFupload({
					"button_placeholder_id":upTagId//设置swfupload按钮附着的element，它来自上一条语句
					,"upload_start_handler":function(){
						//开始上传
						zendform.uploadingTag($("#filepath"));
					}
					,"upload_error_handler":function(file, errorCode, message){
						//上传出错时
						alert("上传错误："+message);
						$("#filepath").next(".uploading").remove();
					}
				},{
					"ju_element":"filepath" //通知上传的额外参数，这里的ju_element必须以ju开头，是返回值的复制element
				});
			}
		}
		,"delurl":BASEURL + "/contractattachment/del"
	}
	,"cost":{
		"gridArg":{
			"url":BASEURL + "/contractcost/listbycontract/contractid/"+$("#id").val()
			,"colModel" : [
				{display: 'ID', name : 'id', width : 20, sortable : true, align: 'center'},
				{display: '项目英文名', name : 'name_en', width : 80, sortable : true, align: 'left'},
				{display: '项目中文名', name : 'name_cn', width : 80, sortable : true, align: 'left'},
				{display: '费用', name : 'cost', width : 80, sortable : false, align: 'left',process:gridHelper.Cash},
				{display: '备注', name : 'price', width : 80, sortable : true, align: 'left'}				
			]
		}
		,"addArg":{
			"url":BASEURL + "/contractcost/add/contractid/"+$("#id").val()
			,"dialog":{"title":"新增费用"}
		}
		,"editArg":{
			"url":BASEURL + "/contractcost/edit/id/{id}"
			,"dialog":{"title":"修改费用"}
		}
		,"delurl":BASEURL + "/contractcost/del"
	}
	,"marks":{
		"gridArg":{
			"url":BASEURL + "/contractmark/listbycontract/contractid/"+$("#id").val()
			,"colModel" : [
				{display: 'ID', name : 'id', width : 20, sortable : true, align: 'center'},
				{display: '唛头', name : 'marks', width : 80, sortable : true, align: 'left'},
				{display: '备注', name : 'price', width : 80, sortable : true, align: 'left'}				
			]
		}
		,"addArg":{
			"url":BASEURL + "/contractmark/add/contractid/"+$("#id").val()
			,"dialog":{"title":"新增唛头"}
		}
		,"editArg":{
			"url":BASEURL + "/contractmark/edit/id/{id}"
			,"dialog":{"title":"修改唛头"}
		}
		,"delurl":BASEURL + "/contractmarkt/del"
	}
	,"press":{
		"gridArg":{
			"url":BASEURL + "/contractpress/listbycontract/contractid/"+$("#id").val()
			,"colModel" : [
				{display: 'ID', name : 'id', width : 20, sortable : true, align: 'center'},
				{display: '计划名称', name : 'press_text', width : 80, sortable : true, align: 'left'},
				{display: '提醒时间', name : 'remind_alarm_time', width : 80, sortable : true, align: 'left'},
				{display: '备注', name : 'price', width : 80, sortable : true, align: 'left'}				
			]
		}
		,"addArg":{
			"url":BASEURL + "/contractpress/add/contractid/"+$("#id").val()
			,"dialog":{"title":"新增计划"}
		}
		,"editArg":{
			"url":BASEURL + "/contractpress/edit/id/{id}"
			,"dialog":{"title":"修改计划"}
		}
		,"delurl":BASEURL + "/contractpresst/del"
	}
	,"rule":{
		"gridArg":{
			"url":BASEURL + "/contractrule/listbycontract/contractid/"+$("#id").val()
			,"colModel" : [
				{display: 'ID', name : 'id', width : 20, sortable : true, align: 'center'},
				{display: '条款英文名', name : 'name', width : 80, sortable : true, align: 'left'},
				{display: '条款中文名', name : 'remind_alarm_time', width : 80, sortable : true, align: 'left'},
				{display: '备注', name : 'price', width : 80, sortable : true, align: 'left'}				
			]
		}
		,"addArg":{
			"url":BASEURL + "/contractrule/add/contractid/"+$("#id").val()
			,"dialog":{"title":"新增条款"}
		}
		,"editArg":{
			"url":BASEURL + "/contractrule/edit/id/{id}"
			,"dialog":{"title":"修改条款"}
		}
		,"delurl":BASEURL + "/contractrulet/del"
	}
}
//当前活动的附属数据
,activeAttachItems = attachmentItems.product
//初始化grid，参数：grid参数,附着的element,
,initGrid = function(gridarg,element){
	gridarg = gridarg || activeAttachItems.gridArg;
	gridarg = $.extend({
		dataType: 'json',		
		buttons : [
			{name: '新增',bclass:"add", onpress : add},
			{name: '编辑',bclass:"edit", onpress : edit},
			{name: '删除',bclass:"delete", onpress : del},
			{separator: true}
		], 
		sortname: "id",
		sortorder: "asc",
		novstripe:true,
		//singleSelect:true,//是否单选
		usepager: false,
		hideOnSubmit:false,//禁用遮照
		useRp: true,
		rp: 15,
		showTableToggleBtn: false,
		id:"",
		width: "99%",
		height: 118
	},gridarg);
	window.grids = element.flexigrid(gridarg).show();
}
//根据选项卡切换grid
,showGrid = function(event,ui){
	var seletedTab = $(ui.panel).find("table:last");
	var activingArgName = seletedTab.attr("id").toString().replace("_list","");
	if(activeAttachItems = attachmentItems[activingArgName])
		initGrid(activeAttachItems.gridArg,seletedTab);
}
,add = function(name,e){
	var top = $(this).offset().top;
	zendform.zendFormCreat(e,$.extend(true,{
		url:BASEURL + "/contract/addproduct/contractid/"+$("#id").val(),
		dialog:{
			width:505,
			height:300/*,
			position:[null,top]*/
		}
	},activeAttachItems.addArg));
}
,edit = function(name,e){
	id = $(e).find(".trSelected")[0].id.toString().replace("row","") || "0";
	if(activeAttachItems.editArg){
		if(activeAttachItems.editArg.url){
			activeAttachItems.editArg.url = activeAttachItems.editArg.url.replace("{id}", id);
		}
	}
	var top = $(this).offset().top;
	zendform.zendFormCreat(e,$.extend(true,{
		dialog:{
			width:505,
			height:300/*,
			position:[null,top]*/
		}
	},activeAttachItems.editArg));
}
,del = function(name,e){
	var ids = $(e).find(".trSelected");
	var idsData = [];
	$.each(ids,function(i,n){
		var uid = n.id.toString().replace("row","") || "0";
		uid = uid;
		idsData.push(uid);
	});
	if(confirm("您确定要删除这"+ids.length+"项数据吗？")){
		$.ajax({
			"url":activeAttachItems.delurl,
			"data":{id:idsData},
			"type":"POST",
			"success":function(data){
				if(data.status > 0){
					var randId = "id_" + Date.parse(new Date());
		        	window.grids.flexReload();
		        	$("<div id='"+randId+"'>"+data.msg+"</div>").dialog({title:"SUCCESS!",height: 140,modal: true});
		        	window.setTimeout(function(){$("#"+randId).dialog("close");},1200);
		        }else{
			        $("<div>ERROR!"+data.msg+"</div>").dialog({title:"ERROR!",height: 140,modal: true});
		        }
			},
			"error":function(){
		    	$("<div>ERROR!<br>服务错误！可能是网络忙！</div>").dialog({title:"ERROR!",height: 140,modal: true});
			}
		});
	}
}
//客户下拉列表与客户代理人的联动
,choiseCustomer = function(){
	var customerE = $("#customer");
	customerE.prepend("<option selected='selected'>选择客户</option>");
	customerE.change(function(){
		$.ajax({
			"url":BASEURL + "/custagent/getitembycust/customerid/"+customerE.val(),
			"dataType":"json",
			"type":"POST",
			"success":function(data){
				if(data){
					var customer_agentE = $("#customer_agent");
					customer_agentE.children().remove(); 
					customer_agentE[0].options.add(new Option("选择联系人","0"));
					$.each(data,function(i, value){
						customer_agentE[0].options.add(new Option(value.name,value.id));
					})
					
				}else{
					
				}
			},
			"error":function(){
				$("<div>ERROR!客户联系人获取失败</div>").dialog({title:"ERROR!",height: 140,modal: true});
			}
		});
	});
}
//客户联系人信息联动
,choiseCustomerAgent = function(){
	var customer_agentE = $("#customer_agent");
	customer_agentE.change(function(){
		$.ajax({
			"url":BASEURL + "/custagent/getitem/id/"+customer_agentE.val(),
			"dataType":"json",
			"type":"POST",
			"success":function(data){
				if(data){
					var cust_emailE = $("#cust_email");
					cust_emailE.val(data.email);
				}else{
					
				}
			},
			"error":function(){
				$("<div>ERROR!客户联系人信息获取失败</div>").dialog({title:"ERROR!",height: 140,modal: true});
			}
		});
	});
}
//汇率联动
,choiseCurrency = function(){
	var currencyE = $("#currency");
	currencyE.prepend("<option selected='selected'>选择货币</option>");
	currencyE.change(function(){
		$.ajax({
			"url":BASEURL + "/currency/getitem/id/"+currencyE.val(),
			"dataType":"json",
			"type":"POST",
			"success":function(data){
				if(data){
					var exchangeE = $("#exchange");
					exchangeE.val(data.exchange);
				}else{
					
				}
			},
			"error":function(){
				$("<div>ERROR!汇率信息获取失败</div>").dialog({title:"ERROR!",height: 140,modal: true});
			}
		});
	});
}
//上传域
,appendSWFupload = function(swfupArg,userArg){
	swfu = new SWFUpload($.extend({
		// Backend Settings
		upload_url: BASEURL + "/file/upload",
		post_params: $.extend({"PHPSESSID": PHPSESSID,"ju_element":"xxx"},userArg),

		// File Upload Settings
		file_size_limit : "2 MB",	// 2MB
		file_types : "*.*",
		file_types_description : "Every File You Want",
		file_upload_limit : "0",

		//upload_start_handler : fileUpSatrt,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,

		// Button Settings
		button_image_url : BASEURL + "/js/swfupload/SmallSpyGlassWithTransperancy_17x18.png",
		button_placeholder_id : "",
		button_width: 18,
		button_height: 18,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		
		// Flash Settings
		flash_url : BASEURL + "/js/swfupload/swfupload.swf",

		custom_settings : {
			upload_target : "zend_up_uploading"
		},
		
		// Debug Settings
		debug: false
	},swfupArg));

	
	/*$("#sltdiv").insertAfter("#mag_thumbnail");
	$("#mag_thumbnail").css("float","left");*/
}
//上传成功共
,uploadSuccess = function(file, serverData) {
	try{
		var response = $.parseJSON(serverData);
	}catch(ex){
		response = serverData;
	}
	try {
		var progress = new FileProgress(file,  this.customSettings.upload_target);
		if(response.FILEID){
			if(response.request){
				$("#" + response.request.ju_element).val(response.FILEID).next(".uploading").remove();
			}
			//progress.setStatus("Thumbnail Created.");
			progress.toggleCancel(false);
		} else {
			this.uploadError(file, 1001, serverData);
		}
	} catch (ex) {
		this.debug(ex);
	}
}
,sub = function(event){
	event = event || window.event;
	var buttonT = $(event.target);
	buttonT.html("正在提交表单...").parent("button").attr({"disabled":"disabled"});
	//查找form
	var Did = "Did_" + Date.parse(new Date());
	var formT = $("#contractform form");
	formT = formT || $(this).find("form");
	
	var reStr = formT.formSerialize ? formT.formSerialize() : formT.serialize();
	$.ajax({
		url: formT.attr("action"),
		data:reStr,
		dataType:"json",
		type:formT.attr("method") || "POST",
		success:function(data) {
			if (data.status == 1) {
				$("<div id='"+Did+"'>成功!"+data.msg+"</div>").dialog({title:"ERROR!",height: 140,modal: true});
				buttonT.html("保存");
				if(grids){
					window.setTimeout(function(){$("#"+Did).dialog("close");},1200);
				}
			}else{
				$("#contractform").html(data['form']);
				$("<div>ERROR!"+data.msg+"</div>").dialog({title:"ERROR!",height: 140,modal: true});
			}
			buttonT.html("保存").parent("button").attr({"disabled":false});
			$("#contract_date,#stocking_time_limit,#transport_time_limit,#stocking_time_limit,#TTprepay_date,#remind_alarm_time").datepicker( $.datepicker.regional[ "zh-CN" ] );			
		},
		error:function(){
			$("<div>ERROR!<br>服务错误！可能是网络忙！</div>").dialog({title:"ERROR!",height: 140,modal: true});
			buttonT.html("保存").parent("button").attr({"disabled":false});
			$("#contract_date,#stocking_time_limit,#transport_time_limit,#stocking_time_limit,#TTprepay_date,#remind_alarm_time").datepicker( $.datepicker.regional[ "zh-CN" ] );
		}
	});
}